/**
 * 
 */
package com.chh.mysso.web.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.chh.mysso.common.model.BaseResult;
import com.chh.mysso.common.utils.CookieUtil;
import com.chh.mysso.common.utils.MD5HashUtil;
import com.chh.mysso.common.utils.SSOConstant;
import com.chh.mysso.common.utils.SessionUtil;
import com.chh.mysso.common.utils.UUIDGenerator;
import com.chh.mysso.core.cache.LoginUserCache;
import com.chh.mysso.core.service.AuthUserService;
import com.chh.mysso.domain.model.dto.AuthUserDTO;
import com.chh.mysso.domain.pojo.command.user.LoginAuthUserRequest;

/**
 * @author chh
 *
 */
@Controller
public class LoginController extends BaseController{
	
	private final static Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private AuthUserService authUserService;

	@Autowired
	private LoginUserCache loginUserCache;
	
	/**
	 * 验证token是否有效
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/login/vali", method = RequestMethod.POST)
	@ResponseBody
	public String valiLoginToken(HttpServletRequest req){
		boolean success = false;
		String resData = null;
		Cookie cookie = CookieUtil.getCookie(req, SSOConstant.LOGIN_USER_SESSION_TOKEN);
		if (cookie != null) {
			AuthUserDTO user = loginUserCache.get(cookie.getValue());
			if (user != null) {
				success = true;
				resData = cookie.getValue();
			}
		}
		return JSON.toJSONString(new BaseResult<String>(success, resData, null));
	}
	
	/**
	 * 登陆提交
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public void doPost(HttpServletRequest req, HttpServletResponse res, LoginAuthUserRequest request){
		try {
			AuthUserDTO user = authUserService.login(request);
			if (user != null) {
				CookieUtil.setCookie(req, res, SSOConstant.LOGIN_USER_SESSION_TOKEN, request.getLoginToken());
				SessionUtil.put(req, SSOConstant.LOGIN_USER_SESSION_TOKEN, MD5HashUtil.toMD5(request.getLoginToken()));
				putLoginUser(req, user);
				if (logger.isInfoEnabled()) {
					logger.info(request.getLoginName() + "用户登录成功！，登录token=" + request.getLoginToken());
				}
				if (StringUtils.isNotBlank(request.getRedirectUrl())) {
					res.sendRedirect(request.getRedirectUrl());
				} else {
					res.sendRedirect(req.getContextPath() + "/index");
				}
			} else {
				res.getWriter().println(JSON.toJSONString(new BaseResult<Boolean>(false, false, "用户登录异常")));
			}
		} catch (Exception e) {
			logger.error("用户登陆失败", e);
		}
	}
	
	public static void main(String[] args) {
		
	}
	
	/**
	 * 跳转登陆也没
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String doGet(HttpServletRequest request, Model model, String redirectUrl){
		String token = CookieUtil.getCookieValue(request, SSOConstant.LOGIN_USER_SESSION_TOKEN);
		if (StringUtils.isBlank(token)) {
			token = UUIDGenerator.getUUID(UUIDGenerator.LOGIN_TOKEN_CODE);
		}
		if (StringUtils.isNotBlank(redirectUrl)) {
			model.addAttribute("redirectUrl", redirectUrl);
		}
		model.addAttribute("token", token);
		return "login.html";
	}
}
